package com.qall.media;

import org.bytedeco.javacpp.avcodec;
import org.bytedeco.javacv.*;
import org.springframework.stereotype.Service;

import java.util.function.Function;

@Service
public class RtspProcess {

    public void rtspToRtmp(String rtspUrl, String rtmpUrl, Function<Frame, Frame> frameProcess) {
        FFmpegFrameGrabber grabber = null;
        try {
            grabber = FFmpegFrameGrabber.createDefault(rtspUrl);
            grabber.setOption("rtsp_transport", "tcp");
            grabber.start();
        } catch (FrameGrabber.Exception e) {
            e.printStackTrace();
        }
        int audioRecord = 1; // 0 = 不录制，1=录制
        int width = 640, height = 480;
        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(rtmpUrl,width,height, audioRecord);
        recorder.setInterleaved(true);
        recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264); // 28
        recorder.setFormat("flv"); // rtmp的类型
        recorder.setFrameRate(25);
        recorder.setImageWidth(width);
        recorder.setImageHeight(height);
        recorder.setPixelFormat(0); // yuv420p
        try {
            recorder.start();
        } catch (FrameRecorder.Exception e) {
            e.printStackTrace();
            return;
        }
        boolean isPlay = true;
        FFmpegFrameGrabber finalGrabber = grabber;

        while (isPlay) {

            Frame frame;

            try {
                frame = finalGrabber.grabFrame();

                frame = frameProcess.apply(frame);
                if (frame == null||frame.image==null) {
                    continue;
                }
                recorder.record(frame);
            } catch (FrameGrabber.Exception | FrameRecorder.Exception e) {
                e.printStackTrace();
            }

        }


    }

//        try {
//            grabber.stop();
//            grabber.release();
//            recorder.stop();
//            recorder.release();
//        } catch (FrameGrabber.Exception | FrameRecorder.Exception e) {
//            e.printStackTrace();
//        }


}


